package com.benchproject.patterns.state;

public class TheWebApp {

	private String username; 
	private String password;
	private Controller controller = new Controller();	
	private int failedLoginAttempts = 0;
	
	private String newUrl;
	
	
	public void login(String username, String password){
		this.username = username;
		this.password = password;
		
		ActionForwardUrl forward = this.controller.forwardTo();
		this.newUrl = forward.getUrl();
	}
	
	public String getNewUrl(){
		return this.newUrl;
	}
	
	
	//inner class representing the controller
	class Controller{
		
		StateMachine stateMachine = new StateMachine();
		Events event;
		
		//main method similar to perform() in struts
		ActionForwardUrl forwardTo(){
			
			boolean credentialsValid = false;
			
			//validate credentials
			if(username.equals("jsmith") 
					&& password.equals("j5m1th")){
				event = Events.USER_SUPPLIES_CORRECT_CREDENTIALS;
			} else {
				if(failedLoginAttempts < 2){
					event = Events.USER_SUPPLIES_INCORRECT_CREDENTIALS;
					failedLoginAttempts++;
				} else {
					event = Events.USER_FAILS_LOGIN_TWICE;
				}
			}
			
			//call statemachine to determind forwarding url
			ActionForwardUrl forward = stateMachine.handleEvent(event);
			
			return forward;
		}
	}
	
}
